const Controller = require('egg').Controller;

class UserController extends Controller {
  // 获取账号
  async index() {
    try {
      let userList = await this.ctx.service.user.getUser();
      this.ctx.body = {
        code: 20000,
        message: '获取账号成功',
        data: userList
      };
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
  // 创建账号
  async create() {
    try {
      let userInfo = this.ctx.request.body;
      let rel = await this.ctx.service.user.addUser(userInfo);
      console.log(rel);
      this.ctx.body = {
        code: 20000,
        message: '增加用户成功'
      };
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
  //  删除
  async destroy() {
    try {
      let id = this.ctx.params.id;
      let rel = await this.ctx.service.user.deleteUser(id);
      console.log(rel);
      this.ctx.body = {
        code: 20000,
        message: '删除用户成功'
      };
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
  // 修改
  async update() {
    try {
      let id = this.ctx.params.id;
      let newInfo = this.ctx.request.body;
      let rel = await this.ctx.service.user.changeUser(id, newInfo);
      console.log(rel);
      this.ctx.body = {
        code: 20000,
        message: '修改用户成功'
      };
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
  //  获取一个用户
  async show() {
    try {
      let id = this.ctx.params.id;
      let userData = await this.ctx.service.user.getOneUser(id);
      this.ctx.body = {
        code: 20000,
        message: '获取一个成功',
        data: userData
      };
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
  // 用户登录
  async login(){
    try {
      let userData = this.ctx.request.body;
      let rel = await this.ctx.service.user.loginCheck(userData);
      let state = rel.state;
      if (state === true) {
        this.ctx.body = {
          code: 20000,
          message: '登录校验成功',
          token: rel.result,
          role: rel.role
        };
      } else if (state === false) {
        this.ctx.body = {
          code: 20000,
          message: '帐号或密码错误或账号被停用'
        };
      } else {
        this.ctx.body = {
          code: 20000,
          message: '没有这个帐号'
        };
      }
    } catch (error) {
      this.ctx.body = {
        code: 50000,
        message: '服务器错误'
      };
    }
  }
}

module.exports = UserController;
